import React, { useState, Key, useEffect } from "react";
import { Button, Form, Input, message } from "antd";
import { useNavigate, useLocation } from "react-router";
import { useForm } from "antd/lib/form/Form";
import {
  reqAddHospitalSet,
  reqUpdateHospitalSet,
  reqGetHospitalSetById,
} from "@/api/hospital/hospitalSet/index";

const AddOrUpdateHospitalSet = () => {
  const navigate = useNavigate();
  // 获取location对象
  const location = useLocation();
  // 拿到数据
  const id = location.state;

  const [form] = useForm();
  // 保存
  const onFinish = async (values: any) => {
    console.log(id);

    if (id) {
      //将id添加到values对象中
      values.id = id;
      await reqUpdateHospitalSet(values);
      message.success("修改医院设置成功");
    }else{
      await reqAddHospitalSet(values);
      message.success("添加医院设置成功");
    }

    navigate(-1);
  };
  // 挂载
  useEffect(() => {
    // 如果有id，请求获取医院设置数据，填在form里

    // 发送请求
    const fetch = async () => {
      const res = await reqGetHospitalSetById(id as number);
      // 设置form的值
      form.setFieldsValue(res);
    };
    if (id) fetch();
  }, []);
  return (
    <>
      <Form
        name="basic"
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        style={{ maxWidth: 1000 }}
        onFinish={onFinish}
        form={form}
      >
        <Form.Item
          label="医院名称"
          name="hosname"
          rules={[{ required: true, message: "请输入医院名称" }]}
        >
          <Input placeholder="医院名称" />
        </Form.Item>

        <Form.Item
          label="医院编码"
          name="hoscode"
          rules={[{ required: true, message: "请输入医院编码" }]}
        >
          <Input placeholder="医院编码" />
        </Form.Item>
        <Form.Item
          label="api基础路径"
          name="apiUrl"
          rules={[{ required: true, message: "请输入api基础路径" }]}
        >
          <Input placeholder="api基础路径" />
        </Form.Item>
        <Form.Item
          label="联系人姓名"
          name="contactsName"
          rules={[{ required: true, message: "请输入联系人姓名" }]}
        >
          <Input placeholder="联系人姓名" />
        </Form.Item>
        <Form.Item
          label="联系人号码"
          name="contactsPhone"
          rules={[
            {
              required: true,
              message: "请输入联系人手机号",
              pattern: /^1[3-9]\d{9}$/,
            },
          ]}
        >
          <Input placeholder="联系人号码" />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Button
            type="primary"
            htmlType="submit"
            style={{ marginRight: "10px" }}
          >
            保存
          </Button>
          <Button
            type="default"
            onClick={() => {
              navigate(-1);
            }}
          >
            返回
          </Button>
        </Form.Item>
      </Form>
    </>
  );
};
export default AddOrUpdateHospitalSet;
